package com.hakgc.rent.web.servlet;

import com.hakgc.rent.entity.User;
import com.hakgc.rent.service.UserService;
import com.hakgc.rent.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.UUID;

/**
 * @author Xing.Jiejian
 * @date 2020/11/18
 */
@WebServlet(name = "AddUserServlet",urlPatterns = "/rent/user/add")
@MultipartConfig
public class AddUserServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 接收基本的数据
        String name = request.getParameter("userName");
        String password = request.getParameter("password");
        User user = new User(name,password);
        // 接收文件对象
        Part part = request.getPart("logoUrl");
        // 获取文件类型 图片类型(IMAGE/JPEG)
        // TODO 就可以限定文件上传类型是否符合要求
        String contentType = part.getContentType();
        // 获取文件大小:单位字节
        // TODO 限定文件大小
        long size = part.getSize();
        //cd ->  form-data; name="logoUrl"; filename="xxx.jpg"
        String cd = part.getHeader("Content-Disposition");
        // 获取原文件名 xxx.jpg
        String filename = cd.substring(cd.lastIndexOf("=") + 2, cd.length() - 1);
        if (filename.length() > 0) {
            // 获取原本文件的后缀
            String extName = filename.substring(filename.lastIndexOf("."));
            // 生成新的文件名
            String uuid = UUID.randomUUID().toString().replace("-", "");
            String newFilename = uuid + extName;
            // 设定文件保存的路径(”/upload“),获取上传目录在服务器中的完整路径
            String savePath = request.getServletContext().getRealPath("/upload");
            // 将文件使用新文件名保存到服务器指定路径
            part.write(savePath + "/" + newFilename);
            user.setLogoUrl("/upload/"+newFilename);
        }

        //调用业务方法保存用户对象
        UserService userService = new UserServiceImpl();
        userService.add(user);

        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.println("<script>");
        out.println("alert('保存成功');");
        out.println("location.href='"+request.getContextPath()+"/login';");
        out.println("</script>");

    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
